import * as XLSX from 'xlsx';

/**
 * 导出数据到Excel文件
 * @param {object} options - 选项
 * @param {object} options.headers - 表头映射, { key: '中文名' }
 * @param {Array<object>} options.data - 要导出的数据数组
 * @param {string} options.fileName - 导出的文件名(不含.xlsx)
 */
export function exportToExcel({ headers, data, fileName = 'export' }) {
  const headerKeys = Object.keys(headers);
  const headerTitles = Object.values(headers);
  
  // 转换数据以匹配表头顺序
  const formattedData = data.map(item => 
    headerKeys.map(key => item[key] ?? '')
  );

  const ws_data = [headerTitles, ...formattedData];
  const ws = XLSX.utils.aoa_to_sheet(ws_data);

  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  XLSX.writeFile(wb, `${fileName}_${new Date().getTime()}.xlsx`);
}

// 您需要安装依赖: npm install xlsx